package com.wootion.cims.general.utils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wootion.cims.dao.*;
import com.wootion.cims.module.basicinformation.plotsetting.model.Building;
import com.wootion.cims.module.basicinformation.plotsetting.model.PlotMessage;
import com.wootion.cims.module.communitypersonal.model.Person;
import com.wootion.cims.module.communityresidence.residencelist.model.City;
import com.wootion.cims.module.communityresidence.residencelist.model.Provincial;
import com.wootion.cims.module.communityresidence.residencelist.model.Residence;
import com.wootion.cims.module.systemsetting.dictionary.model.SysDictionary;
import com.wootion.cims.module.systemsetting.polt.model.SysPlot;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class ChackUtil {

    @Resource
    private SysUserRoleDao sysUserRoleDao;
    @Resource
    private SysRoleDao sysRoleDao;
    @Resource
    private SysUserCommunityDao sysUserCommunityDao;
    @Resource
    private SysCommunityDao sysCommunityDao;
    @Resource
    private SysPlotDao sysPlotDao;
    @Resource
    private SysDictionaryDao sysDictionaryDao;
    @Resource
    private CityDao cityDao;
    @Resource
    private ProvincialDao provincialDao;
    @Autowired
    RedisUtil redisUtil;

    @Autowired(required = false)
    PersonDao personDao;

    @Autowired(required = false)
    ResidenceDao residenceDao;

    public String dataChack(String data, String type, String communityId, String plotId,String abode){
        switch (type) {
            case "身份证号": {
                boolean validatedAllIdcard = IdcardValidatorUtil.isValidatedAllIdcard(data);
                if (!validatedAllIdcard)
                    return "身份号不合法";
                boolean b = checkIdNumber(data);
                if (!b)
                    return "身份证号无法解析出出生时间,性别或者年龄";
                QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("id_number", data);
                queryWrapper.eq("enabled", true);
                Person person1 = personDao.selectOne(queryWrapper);

                QueryWrapper<Person> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("id_number", data);
                queryWrapper2.eq("enabled", false);
                queryWrapper2.eq("dr_inset","0");
                Person person2 = personDao.selectOne(queryWrapper2);

                if (Optional.ofNullable(person1).isPresent())
                    return "身份证号重复";

                if (Optional.ofNullable(person2).isPresent())
                    return "身份证号重复";
                break;
            }
            case "姓名": {
                boolean matches = data.matches("^[\\u4E00-\\u9FA5A-Za-z0-9]+$");
                if (!matches)
                    return "姓名不合法";

                break;
            }
            case "民族": {
                boolean codeByDesc = NationalityEnum.getCodeByDesc(data);
                if (!codeByDesc)
                    return "民族不合法";

                break;
            }
            case "手机号": {
                int length = data.length();
                if (length != 11)
                    return "手机号不合法";
                boolean matches = data.matches("^[0-9]*$");
                if (!matches)
                    return "手机号不合法";

                break;
            }
            case "户籍地": {
                if (!data.equals("辖区内") && !data.equals("辖区外/集体户"))
                    return "户籍地不合法";

                break;
            }
            case "户主或与户主关系": {
                QueryWrapper<SysDictionary> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("name", "户主与户主关系");
                if ("户主".equals(data)) {
                    return null;
                }
                SysDictionary sysDictionary = sysDictionaryDao.selectOne(queryWrapper);
                if (Optional.ofNullable(sysDictionary).isPresent()) {
                    String value = sysDictionary.getValue();
                    String[] split = value.split(",");
                    for (String s : split) {
                        if (s.equals(data)) {
                            return null;
                        }
                    }
                    return "户主或与户主关系字段不合法";
                }

                break;
            }
            case "户口性质": {
                QueryWrapper<SysDictionary> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("name", "户口性质");
                SysDictionary sysDictionary = sysDictionaryDao.selectOne(queryWrapper);
                if (Optional.ofNullable(sysDictionary).isPresent()) {
                    String value = sysDictionary.getValue();
                    String[] split = value.split(",");
                    for (String s : split) {
                        if (s.equals(data)) {
                            return null;
                        }
                    }
                    return "户口性质字段不合法";
                }

                break;
            }
            case "原籍类型": {
                QueryWrapper<SysDictionary> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("name", "原籍类型");
                SysDictionary sysDictionary = sysDictionaryDao.selectOne(queryWrapper);
                if (Optional.ofNullable(sysDictionary).isPresent()) {
                    String value = sysDictionary.getValue();
                    String[] split = value.split(",");
                    for (String s : split) {
                        if (s.equals(data)) {
                            return null;
                        }
                    }
                    return "原籍类型字段不合法";
                }

                break;
            }
            case "文化程度": {
                QueryWrapper<SysDictionary> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("name", "文化程度");
                SysDictionary sysDictionary = sysDictionaryDao.selectOne(queryWrapper);
                if (Optional.ofNullable(sysDictionary).isPresent()) {
                    String value = sysDictionary.getValue();
                    String[] split = value.split(",");
                    for (String s : split) {
                        if (s.equals(data)) {
                            return null;
                        }
                    }
                    return "文化程度字段不合法";
                }

                break;
            }
            case "婚姻状况": {
                QueryWrapper<SysDictionary> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("name", "婚姻状况");
                SysDictionary sysDictionary = sysDictionaryDao.selectOne(queryWrapper);
                if (Optional.ofNullable(sysDictionary).isPresent()) {
                    String value = sysDictionary.getValue();
                    String[] split = value.split(",");
                    for (String s : split) {
                        if (s.equals(data)) {
                            return null;
                        }
                    }
                    return "婚姻状况字段不合法";
                }

                break;
            }
            case "户籍编号": {
                int length = data.length();
                if (length != 9)
                    return "户籍编号不合法";
                boolean matches = data.matches("^[0-9]*$");
                if (!matches)
                    return "户籍编号不合法";

                break;
            }
            case "户籍派出所": {
                char cArr[] = data.toCharArray();//将字符串转换为字符数组
                for (int i = 0; i < cArr.length; i++) {
                    int ascii = String.valueOf(cArr[i]).hashCode();
                    if ((ascii >= 65 && ascii <= 90) || (ascii >= 97 && ascii <= 122)) {
                        return "户籍派出所包含字母";
                    }
                }
                break;
            }
            case "出生地": {
                if (Optional.ofNullable(data).isPresent() && StringUtil.isNullOrEmpty(data))
                    return "出生地不可为空";

                break;
            }
            case "流动人口": {
                QueryWrapper<SysDictionary> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("name", "流动人口");
                SysDictionary sysDictionary = sysDictionaryDao.selectOne(queryWrapper);
                if (Optional.ofNullable(sysDictionary).isPresent()) {
                    String value = sysDictionary.getValue();
                    String[] split = value.split(",");
                    for (String s : split) {
                        if (s.equals(data)) {
                            return null;
                        }
                    }
                    return "流动人口字段不合法";
                }
                break;
            }
            case "社会保障": {
                if (!data.equals("城镇医疗保险") && !data.equals("城镇养老保险"))
                    return "社会保障信息不合法";

                break;
            }
            case "结婚日期": {
                SimpleDateFormat bDate = new SimpleDateFormat("yyyy-MM-dd");
                Date parse = null;
                try {
                    parse = bDate.parse(data);
                } catch (ParseException e) {
                    return "结婚日期不合法,请使用yyyy-MM-dd格式";
                }
                if (!Optional.ofNullable(parse).isPresent()) {
                    return "结婚日期不合法,请使用yyyy-MM-dd格式";
                }

                break;
            }
            case "计生类别": {
                QueryWrapper<SysDictionary> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("name", "生计类别");
                SysDictionary sysDictionary = sysDictionaryDao.selectOne(queryWrapper);
                if (Optional.ofNullable(sysDictionary).isPresent()) {
                    String value = sysDictionary.getValue();
                    String[] split = value.split(",");
                    for (String s : split) {
                        if (s.equals(data)) {
                            return null;
                        }
                    }
                    return "计生类别字段不合法";
                }

                break;
            }
            case "子女信息": {
//                if (Optional.ofNullable(data).isPresent() && StringUtil.isNullOrEmpty(data)) {
//                    return "子女信息不可为空";
//                }

                break;
            }
            case "工作类别": {
                QueryWrapper<SysDictionary> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("name", "工作类别");
                SysDictionary sysDictionary = sysDictionaryDao.selectOne(queryWrapper);
                if (Optional.ofNullable(sysDictionary).isPresent()) {
                    String value = sysDictionary.getValue();
                    String[] split = value.split(",");
                    for (String s : split) {
                        if (s.equals(data)) {
                            return null;
                        }
                    }
                    return "工作类别字段不合法";
                }

                break;
            }
            case "健康状况": {
                String[] split = data.split("、");
                for (String s : split) {
                    if (!s.equals("健康") && !s.equals("一般") && !s.equals("高血压") && !s.equals("心脏病") &&
                            !s.equals("白血病") && !s.equals("糖尿病") && !s.equals("心脑血管病症") && !s.equals("癌症") &&
                            !s.equals("其他病症"))
                        return "健康状况信息不合法";
                }
                    break;
            }
            case "特殊人群": {
                String[] split = data.split("、");
                for (String s : split) {
                    if (!s.equals("特长居民") && !s.equals("劳教人员") && !s.equals("特困") && !s.equals("矫正人群") &&
                            !s.equals("劳改人员") && !s.equals("现役") && !s.equals("下岗失业人员"))
                        return "特殊人群信息不合法";
                }
                    break;
            }
            case "综合信息": {
                String[] split = data.split("、");
                for (String s : split) {
                    if (!s.equals("残疾人") && !s.equals("低保") && !s.equals("优抚") && !s.equals("党员") &&
                            !s.equals("租户") && !s.equals("老年人"))
                        return "综合信息不合法";
                }
                break;
            }
            case "居住地址": {
                if(!checkAddress(data, communityId, plotId,abode)){
                    return "居住地址错误";
                }
                break;
            }
            case "工作单位": {

            }
        }
        return null;
    }

    /**
     * @param communityId 社区id
     * @param plotId         小区id
     * @param address        地址
     * @return
     */
    public String checkResidence(String abode,String communityId, String plotId, String address) {
        if(StringUtils.hasText(address)){
            if("辖区内".equals(abode)){//辖区内
                if(!address.contains("-")){
                    return null;
                }
                if (address.split("-").length != 2) {
                    return null;
                }
                //格式：   2栋/3单元-1201室   A区-A504
                //楼房
                String address1 = address.split("-")[0];//楼栋和单元 或者是区域
                String houseNumber = address.split("-")[1];//房间号
                if (!StringUtils.hasText(address1) || !StringUtils.hasText(houseNumber)) {
                    return null;
                }
                LambdaQueryWrapper<Residence> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Residence::getCommunityId, communityId);
                queryWrapper.eq(Residence::getPlotId, plotId);
                queryWrapper.eq(Residence::getAddress, address1);
                queryWrapper.eq(Residence::getHouseNumber, houseNumber);
                Residence residence = residenceDao.selectOne(queryWrapper);
                return Objects.nonNull(residence) ? residence.getId():null;
            }else {//辖区外
                return null;
            }
        }else {
            return null;
        }
    }


    /**
     * 校验地址，返回false是地址不通过  true是通过
     * @param address 地址
     * @return
     */
    public boolean checkAddress(String address, String communityId, String plotId,String abode) {
        if (StringUtils.hasText(address)) {
            if("辖区内".equals(abode)){//辖区内
                if(!address.contains("-")){
                    return false;
                }
                if (address.split("-").length != 2) {
                    return false;
                }
                //格式：   2栋/3单元-1201室   A区-A504
                //楼房
                String prefix = address.split("-")[0];//楼栋和单元 或者是区域
                String suffix = address.split("-")[1];//房间号
                if (!StringUtils.hasText(prefix) || !StringUtils.hasText(suffix)) {
                    return false;
                }
                LambdaQueryWrapper<Residence> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Residence::getCommunityId, communityId);
                queryWrapper.eq(Residence::getPlotId, plotId);
                queryWrapper.eq(Residence::getAddress, prefix);
                queryWrapper.eq(Residence::getHouseNumber, suffix);
                queryWrapper.eq(Residence::getEnabled, true);
                Residence residence = residenceDao.selectOne(queryWrapper);
                return Objects.nonNull(residence);
            }else {//辖区外
                if(address.contains("-")){
                    String[] addres = address.split("-");
                    if(addres.length>3){
                        return false;
                    }
                    //河北省-三河市-燕郊镇

                    LambdaQueryWrapper<Provincial> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(Provincial::getProvincial,addres[0]);
                    Provincial provincial = provincialDao.selectOne(queryWrapper);

                    LambdaQueryWrapper<City> queryWrapper2 = new LambdaQueryWrapper<>();
                    queryWrapper2.eq(City::getCityName,addres[1]);
                    City city = cityDao.selectOne(queryWrapper2);

                    return Objects.nonNull(provincial) && Objects.nonNull(city) && provincial.getId().equals(city.getParentId());
                }else {
                    //河北省
                    LambdaQueryWrapper<Provincial> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(Provincial::getProvincial,address);
                    Provincial provincial = provincialDao.selectOne(queryWrapper);
                    return Objects.nonNull(provincial);
                }
            }
        }else {//如果地址是空的
            return true;
        }
    }

    private boolean checkIdNumber(String string){
        //根据身份证号设置年龄,出生日期,性别
        int ageFromIdCard = IdCardNumberUtils.getAgeFromIdCard(string);
        String birthDayFromIdCard = IdCardNumberUtils.getBirthDayFromIdCard(string);
        Object sex_by_string = IdCardNumberUtils.getSexFromIdCard(string).get("sex_by_string");

        if (!Optional.ofNullable(birthDayFromIdCard).isPresent() || ageFromIdCard ==0 || !Optional.ofNullable(sex_by_string).isPresent()){
            return false;
        }else {
            return true;
        }
    }


}
